<?php

namespace App\Http\Controllers\Api;

use App\Http\Models\Activity;
use App\Http\Models\Member;
use App\Http\Models\SmsLog;
use App\Models\Category;
use App\Services\SmsService;
use App\Support\Data;
use Carbon\Carbon;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator as FacadesValidator;
use Overtrue\EasySms\EasySms;
use zgldh\QiniuStorage\QiniuStorage;

/**
 * 基础系统操作
 *
 * @Author hechengwei
 * @email chichiooo@sina.com
 * @DateTime 2022-03-08
 */
class SystemController extends BaseController
{

    /**
     * 发送验证码
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2022-03-02
     * @param Request $request
     * @return json
     */
    public function sendCode(Request $request)
    {

        $rules = [
            'phone' => ['required', 'mobile'],
            'type' => ['required'],
        ];

        $message = [
            'phone.required' => '请输入手机号码',
            'phone.mobile' => '手机号码格式有误',
            'type.required' => '缺少参数',
        ];

        $payload = $request->only('phone', 'type');

        $validator = FacadesValidator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }

        if ($payload['type'] == 'REG') {
            if (Member::where('username', $payload['phone'])->first()) {
                return fail_message('该手机号已注册！');
            }
        } elseif ($payload['type'] == 'PWD') {
            $info = Member::where('username', $payload['phone'])->first();
            if (empty($info)) {
                return fail_message('该手机号未注册');
            }
        }

        // 查询今日发送条数
        $count = SmsLog::whereDate('add_time', Carbon::today())->where(['phone' => $payload['phone']])->count();

        if ($count >= 10) {
            return fail_message('发送次数过多');
        }

        // 发送验证码
        $res = SmsService::sendCode($payload['phone'], mt_rand(111111, 999999), $payload['type']);

        if (isset($res['yuntongxun']['status']) && $res['yuntongxun']['status'] == 'success') {
            return success([], '发送成功', 200);
        } else {
            return fail_message('发送次数过多');
        }
    }


    public static $config = [
        // HTTP 请求的超时时间（秒）
        'timeout' => 5.0,

        // 默认发送配置
        'default' => [
            // 网关调用策略，默认：顺序调用
            'strategy' => \Overtrue\EasySms\Strategies\OrderStrategy::class,

            // 默认可用的发送网关
            'gateways' => [
                // 'aliyun',
                'yuntongxun'
            ],
        ],
        // 可用的网关配置
        'gateways' => [
            'errorlog' => [
                'file' => '/tmp/easy-sms.log',
            ],
            // 'aliyun' => [
            // 	'access_key_id' => 'LTAI5tGn9FJ4LYAzL3BaftP4',
            // 	'access_key_secret' => 'aS5AJU6ZZeGVq0el3ITjeFUX9U9g8P',
            // 	'sign_name' => '凯斯通',
            // ],
            'yuntongxun' => [
                'app_id'         => '2c94811c85c276590185fb76ae3403da', // 消化界应用id
                'account_sid'    => '8aaf0708591604f301591742cc90010f',
                'account_token'  => 'd925c1d7247144cfb0e16c174f10d618',
                'is_sub_account' => false,
            ]

        ],
        'SMS' => [
            'IDCARD' => '1660849', // 身份验证验证码
            'LOGIN' => '1660849', // 登录确认验证码
            'REG' => '1660849', // 用户注册验证码
            'PWD' => '1660849', // 修改密码验证码
            'INFO' => '1660849', // 信息变更验证码
            'CURRENCY' => '1660849', //通用

        ],
    ];
    /**
     * 发送验证码
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2022-03-02
     * @param Request $request
     * @return json
     */
    public function sendCode11(Request $request)
    {

        $easySms = new EasySms(self::$config);

        try {

            // $res = $easySms->send($phone, [
            //     // 'content'  => '您的验证码为: 6379',
            //     'template' => '1186212',
            //     'data' => [
            //         // 'code' => $code
            //         '123456'
            //     ],
            // ]);
            // dd($res);
            // return $res;
            $code = rand(1000, 9999);
            $data = [$code];

            // $easySms = new EasySms($config);
            $result  = $easySms->send('18032670023', [
                'template' => self::$config['SMS']['INFO'],
                'data'     => $data
            ]);

            return $result;
        } catch (Exception $e) {

            dd($e);

            //     return [];
        }
    }


    /**
     * 上传图片
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2022-03-03
     * @param Request $request
     * @return json
     */
    public function upload(Request $request)
    {

        if ($request->isMethod('POST')) {
            Log::notice('上传文件开始');
            if ($request->hasFile('file')) {
                // try {
                $file = $request->file('file');
                Log::notice('file size : ' . $file->getSize() / 1024);
                if (($file->getSize() / 1024) > 51200) {
                    return fail_message('上传文件最大不能超过50MB');
                }

                $clientName = $file->getClientOriginalName();
                $file_name = explode('.', $clientName);

                // Log::notice('file:' . json_encode($file_name));

                $model = $request->input('model') ?? 'default';
                $expert_name = $request->input('expert_name') ?? '';

                // Log::notice('model:'.$model);

                // 允许上传的图片后缀
                $allow_ext = [
                    "png", "jpg", "jpeg", "gif",
                    "doc", "docx", "wps",
                    "xls", "xlsx",
                    "pdf",
                    "txt",
                    "mp4", "mp3", "avi",
                    "json", "html",
                    "ppt", "pptx",
                    "zip", "rar", "tar", "7z"
                ];


                $ext = $file->getClientOriginalExtension(); // 扩展名
                Log::notice('后缀名：' . $ext);
                $allow_ext_f = array_flip($allow_ext);

                // if (in_array($ext, $allow_ext)) {
                if (isset($allow_ext_f[$ext])) {
                    // 如果是上传协议
                    if ($model == 'agreement') {
                        $agreementName = '劳务协议 - ' . date('Ymd') . ' - ' . $expert_name;
                        $fileName = $model . '/' . $agreementName . '.' . $ext;
                    } elseif ($model == 'medical') {
                        // 如果是上传病例资料，需要model = medical
                        $fileName = 'medical/file/' . date('Y/m/d') . '/' . uniqid() . '/' . $file_name[0] . '.' . $ext;
                    } else {
                        // uniqid 获取一个带前缀、基于当前时间微秒数的唯一ID
                        $fileName = $model . '/' . date('YmdHis') . '-' . uniqid() . '.' . $ext; // 设置文件的名称,如:
                    }


                    // Log::notice('fileName: '.config('filesystems.disks.qiniu.domains.https').$fileName);
                    // 保存写法2
                    $path = $file->getRealPath(); // 临时绝对路径

                    // $filePath = 'uploads/' . date('Ymd') . $fileName;//文件路径
                    $res = qiniu_upload($path, $fileName, $ext);
                    // $res = QiniuStorage::disk('qiniu')->put($fileName, file_get_contents($path));

                    // Log::notice('返回信息：'.json_encode($res));
                    //判断是否上传成功，返回上传的图片路径(字符串)
                    if ($res) {

                        Log::notice('上传成功');

                        // Log::notice(json_encode(['file_name' => $file_name[0],'url' =>qnUrl().$fileName]));

                        // return success(['file_name' => $file_name[0], 'url' => qnUrl() . $fileName, 'agreementName' => $agreementName ?? ''], '上传成功');
                        return success(['file_name' => $file_name[0], 'url' => $res, 'agreementName' => $agreementName ?? ''], '上传成功');
                    } else {
                        return fail_message('上传失败');
                    }
                } else {
                    Log::notice('不支持当前文件格式');
                    return fail_message('不支持当前文件格式');
                }
                // } catch (Exception $e) {
                // Log::notice($e);
                // return fail_message('上传失败');
                // }
            } else {
                return fail_message('请上传图片');
            }
        } else {
            return fail_message('非法请求');
        }
    }


    /**
     * 获取用户身份
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2022-12-19
     * @return void
     */
    public function userType()
    {
        $list = [['id' => 1, 'name' => '医护人员/医疗人员'], ['id' => 2, 'name' => '医药/医疗器械企业人员'], ['id' => 3, 'name' => '游客']];
        if (!empty($list)) {
            return success($list);
        } else {
            return fail_message('失败');
        }
    }


    /**
     * 获取所有分类
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2022-03-09
     * @return json
     */
    public function category(Request $request)
    {
        // $payload = $request->only('type', 'name');

        $model = new Category();
        $cate  = $model->getList([], ['id', 'title as name', 'parent_id as type']);
        $cate = $cate->sortBy('sort');

        return success(array_values($cate->toArray()));
    }


    /**
     * 根据活动id获取分类
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2023-02-02
     * @return json
     */
    public function categoryByActivity(Request $request)
    {
        // return success();
        $rules = [
            'act_id' => ['required'],
        ];

        $message = [
            'act_id.required' => '缺少活动ID',
        ];

        $payload = $request->only('act_id');

        $validator = FacadesValidator::make($payload, $rules, $message);

        // 验证格式
        if ($validator->fails()) {
            return fail_message($validator->errors()->first());
        }


        $activity_cate_ids = Activity::find($payload['act_id'])->category_ids ?? '';
        // dd($activity_cate_ids);
        $model = new Category();
        $where['category_ids'] = explode(',', $activity_cate_ids);
        $cate  = $model->getList($where, ['id', 'title as name', 'parent_id as type']);
        $cate = $cate->sortBy('sort');

        return success(array_values($cate->toArray()));
    }

    /**
     * 获取七牛云的token
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2023-04-21
     * @return void
     */
    public function getQiniuToken()
    {
        $disk = QiniuStorage::disk('qiniu');
        $token = $disk->uploadToken();
        return success(['token' => $token]);
    }

    /**
     * 所有选项
     *
     * @Author hechengwei
     * @email chichiooo@sina.com
     * @DateTime 2024-06-24
     * @return void
     */
    public function checkBox()
    {
        $bigAttachmentFiles = json_decode('[{"name":"\u7528 Redis \u5b9e\u73b0\u4e00\u4e2a\u5206\u5e03\u5f0f\u9501 - \u5f15\u6d41\u8bfe\u7248\u672c.pptx","url":"http:\/\/resource.hengruimi.com\/mi\/20240626\/gCdWdnxSNoeRx8NgGfZ0eBoIckuvPYih.pptx","extension":".pptx"},{"name":"\u7528 Redis \u5b9e\u73b0\u4e00\u4e2a\u5206\u5e03\u5f0f\u9501 - \u5f15\u6d41\u8bfe\u7248\u672c.pptx","url":"http:\/\/resource.hengruimi.com\/mi\/20240626\/gCdWdnxSNoeRx8NgGfZ0eBoIckuvPYih.pptx","extension":".pptx"}]', true);
        $body = "回复内容：\n";
        foreach ($bigAttachmentFiles as $index => $attachment) {
            $body .= ' <p>
            <span>' . $index + 1 . ' <a href=' . $attachment['url'] . '" download=' . $attachment['name'] . '">' . $attachment['name'] . '</a> </span>
        </p>' . "\n";
        }
        dd($body);
        $result = [
            'sex' =>  [
                ['id' => 1, 'name' => '男'],
                ['id' => 2, 'name' => '女']
            ],
            'source' => [
                ['id' => 1, 'name' => '消化科'],
                ['id' => 2, 'name' => '内科'],
                ['id' => 3, 'name' => '心理科'],
                ['id' => 4, 'name' => '其他'],
            ],
            'bim_radio' => [
                ['id' => 1, 'name' => '偏瘦'],
                ['id' => 2, 'name' => '标准'],
                ['id' => 3, 'name' => '微胖'],
                ['id' => 4, 'name' => '肥胖'],
                ['id' => 5, 'name' => '重度肥胖'],
            ],
            'symptom' => [
                ['id' => 1, 'name' => '腹部疼痛/不适'],
                ['id' => 2, 'name' => '腹胀'],
                ['id' => 3, 'name' => '嗳气'],
                ['id' => 4, 'name' => '早饱'],
                ['id' => 5, 'name' => '餐后饱胀'],
                ['id' => 6, 'name' => '恶心'],
                ['id' => 7, 'name' => '呕吐'],
                ['id' => 8, 'name' => '食欲减退'],
                ['id' => 9, 'name' => '体重减轻'],
                ['id' => 10, 'name' => '焦虑抑郁'],
                ['id' => 11, 'name' => '其他'],
            ],
            'disease_code' => [
                ['id' => 1, 'name' => '新发'],
                ['id' => 2, 'name' => '已确诊疾病']
            ],
            'drink_alcohol' => [
                ['id' => 1, 'name' => '是'],
                ['id' => 2, 'name' => '否']
            ],
            'smoking_history' =>  [
                ['id' => 1, 'name' => '是'],
                ['id' => 2, 'name' => '否']
            ],
            'family_historyL' =>  [
                ['id' => 1, 'name' => '是'],
                ['id' => 2, 'name' => '否']
            ],
            'past_historyL' => [
                ['id' => 1, 'name' => '是'],
                ['id' => 2, 'name' => '否']
            ],
            'allergy' =>  [
                ['id' => 1, 'name' => '无'],
                ['id' => 2, 'name' => '有']
            ],
            'check' =>  [
                ['id' => 1, 'name' => '是'],
                ['id' => 2, 'name' => '否']
            ],
            'check_true' =>  [
                ['id' => 1, 'name' => '体格'],
                ['id' => 2, 'name' => '实验室检查结果'],
                ['id' => 3, 'name' => '影像学检查结果'],
                ['id' => 4, 'name' => '病理检查结果'],
                ['id' => 5, 'name' => '其他检查结果'],
            ],

            'check_false' =>  [
                ['id' => 1, 'name' => '不知晓'],
                ['id' => 2, 'name' => '不重视'],
                ['id' => 3, 'name' => '担心费用问题'],
                ['id' => 4, 'name' => '没有出现明显症状'],
                ['id' => 5, 'name' => '工作忙，没有时间检查'],
                ['id' => 6, 'name' => '其他'],
            ],
            'treatment' =>  [
                ['id' => 1, 'name' => '是'],
                ['id' => 2, 'name' => '否']
            ],
            'treatment_return_visit' => [
                ['id' => 1, 'name' => '是'],
                ['id' => 2, 'name' => '否']
            ],
            'digestive_diseases' =>  [
                ['id' => 1, 'name' => '体格'],
                ['id' => 2, 'name' => '实验室检查结果'],
                ['id' => 3, 'name' => '影像学检查结果'],
                ['id' => 4, 'name' => '病理检查结果'],
                ['id' => 5, 'name' => '其他检查结果'],
            ],
            'helicobacter_pylori' => [['id' => 1, 'name' => '阳性'], ['id' => 2, 'name' => '阴性']],
            'comorbidities' => [
                ['id' => 1, 'name' => '焦虑(汉密尔顿焦虑量表评分)'],
                ['id' => 2, 'name' => '抑郁(汉密尔顿焦虑量表评分)'],
                ['id' => 3, 'name' => '其他'],
            ],
            'disease_identify' =>  [
                ['id' => 1, 'name' => '是'],
                ['id' => 2, 'name' => '否']
            ],
            'disease_diagnosis' => [
                ['id' => 1, 'name' => '慢性胃炎'],
                ['id' => 2, 'name' => '消化性溃疡'],
                ['id' => 3, 'name' => '功能性消化不良'],
                ['id' => 4, 'name' => '其他'],
            ],
            'disease_comorbidities' =>  [
                ['id' => 1, 'name' => '无'],
                ['id' => 2, 'name' => '焦虑抑郁症'],
                ['id' => 3, 'name' => '其他'],

            ],
            'treatment_plan' => [['id' => 1, 'name' => '胃苏颗粒']],
            'treatment_situation' =>  [
                ['id' => 1, 'name' => '是'],
                ['id' => 2, 'name' => '否']
            ],
            'treatment_dose' =>  [
                ['id' => 1, 'name' => '是'],
                ['id' => 2, 'name' => '否']
            ],
            'adversereaction' =>  [
                ['id' => 1, 'name' => '无'],
                ['id' => 2, 'name' => '有']
            ],
            'adversereaction_group' => [
                ['id' => 1, 'name' => '头疼'],
                ['id' => 2, 'name' => '头晕'],
                ['id' => 3, 'name' => '恶心'],
                ['id' => 4, 'name' => '呕吐'],
                ['id' => 5, 'name' => '腹泻'],
                ['id' => 6, 'name' => '肌痛'],
                ['id' => 7, 'name' => '关节痛'],
                ['id' => 8, 'name' => '骨痛'],
                ['id' => 9, 'name' => '背痛'],
                ['id' => 10, 'name' => '肢体疼痛'],
                ['id' => 11, 'name' => '流感样疾病'],
                ['id' => 12, 'name' => '寒颤'],
                ['id' => 13, 'name' => '疲劳'],
                ['id' => 14, 'name' => '乏力'],
                ['id' => 15, 'name' => '疼痛'],
                ['id' => 16, 'name' => '其他'],

            ],
            'adversereaction_immediately' =>  [
                ['id' => 1, 'name' => '是'],
                ['id' => 2, 'name' => '否']
            ],
            'adversereaction_degree' => [
                ['id' => 1, 'name' => '轻度'],
                ['id' => 2, 'name' => '中度'],
                ['id' => 3, 'name' => '重度'],
            ],
            'adversereaction_related' => [
                ['id' => 1, 'name' => '肯定'],
                ['id' => 2, 'name' => '很可能'],
                ['id' => 3, 'name' => '可能'],
                ['id' => 4, 'name' => '可能无关'],
                ['id' => 5, 'name' => '待评价'],
                ['id' => 6, 'name' => '无法评价'],
            ],
            // 中医证型
            'tcm_syndrome_type' => [
                ['id' => 1, 'name' => '肝郁气滞症'],
                ['id' => 2, 'name' => '气滞型胃脘痛'],
            ],
        ];
        return success($result);
    }
}
